cimport numpy as np
import numpy as np
cimport cython

ctypedef fused scalar_t:
    float
    double

@cython.boundscheck(False)
@cython.wraparound(False)
@cython.cdivision(True)
def nms_cpu(np.ndarray[scalar_t, ndim=2] dets, scalar_t thresh):

    if dets.shape[0] == 0:
        return []

    scores = dets[:, 0]
    x1 = dets[:, 1]
    y1 = dets[:, 2]
    x2 = dets[:, 3]
    y2 = dets[:, 4]

    areas = (x2 - x1 + 1) * (y2 - y1 + 1)
    cdef scalar_t[::1] areas_view = areas
    order = scores.argsort()[::-1]
    cdef long[::] order_view = order

    ndets = dets.shape[0]
    suppressed = np.zeros((ndets), dtype=np.long)
    cdef long[::1] suppressed_view = suppressed

    cdef scalar_t ix1, iy1, ix2, iy2, iarea, xx1, yy1, xx2, yy2, w, h, inter, ovr
    cdef Py_ssize_t _i, _j, i, j

    cdef scalar_t[:] x1_view = x1
    cdef scalar_t[:] y1_view = y1
    cdef scalar_t[:] x2_view = x2
    cdef scalar_t[:] y2_view = y2

    for _i in range(ndets):
        i = order_view[_i]
        if suppressed_view[i] == 1:
            continue
        ix1 = x1_view[i]
        iy1 = y1_view[i]
        ix2 = x2_view[i]
        iy2 = y2_view[i]
        iarea = areas_view[i]
        for _j in range(_i + 1, ndets):
            j = order_view[_j]
            if suppressed_view[j] == 1:
                continue
            xx1 = max(ix1, x1_view[j])
            yy1 = max(iy1, y1_view[j])
            xx2 = min(ix2, x2_view[j])
            yy2 = min(iy2, y2_view[j])
            w = max(0.0, xx2 - xx1 + 1)
            h = max(0.0, yy2 - yy1 + 1)
            inter = w * h
            ovr = inter / (iarea + areas_view[j] - inter)
            if ovr >= thresh:
                suppressed_view[j] = 1

    return np.where(suppressed == 0)[0]